﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using BaseHelper.Encrypt;
using System.Windows.Forms;

namespace BaseHelper.Text
{
    public class TextToImage
    {
    
        public static string CreateImage(string TempFullPath,string Text, int Width,int Height,string FontName, string FontColor)
        {
            int fontSize = TextFontSizeHelper.CalcFontSize(Text, Width,Height);
            return CreateImage(TempFullPath, Text, Width, Height, FontName, fontSize, FontColor);

        }
        public static string CreateImage(string TempFullPath,string Text, int Width,int Height,string FontName, int FontSize, string FontColor)
        {
            try
            {
                string Sign = Text + "," + Width.ToString() + "," + Height.ToString() + "," + FontName + "," + FontSize.ToString() + "," + FontColor;
                string Path = TempFullPath + "TextImage_" + Md5Helper.Encrypt(Sign) + ".jpg";
                if (File.Exists(Path))
                    return Path;

         
                Font font = new Font(FontName, FontSize, FontStyle.Regular);
                Color color = ToolsHelper.ColorHexToRgb(FontColor);
                SolidBrush brush = new SolidBrush(color);
                Bitmap image = new Bitmap(Width, Height);
                Graphics g = Graphics.FromImage(image);
                Rectangle rect = new Rectangle(0, 0, Width, Height);
                g.FillRectangle(Brushes.Black, rect);

                //int charSpace = 0;
                //int maxLine = Width / (FontSize + charSpace);

                //for (int i = 0; i < Text.Length; i++)
                //{
                //    int x = i % maxLine;
                //    int y = i / maxLine;
                    
                //    PointF pf = new PointF(x * (FontSize + charSpace), y * (FontSize + charSpace));
                //    g.DrawString(Text[i].ToString(), font, brush, pf);

                //}
                 
                 g.DrawString(Text, font, brush, rect);

                //暂时屏蔽下,分行,因为有时候一行右侧会出去
                //int LineHeight = FontSize + (int)Math.Round(FontSize * 0.3f, 1) + 2;
                //string[] Lines = Text.Replace("\r","").Contains("\n")?Text.Split('\n'):new string[]{Text};
                //for(int i=0;i<Lines.Length;i++)
                //    g.DrawString(Lines[i], font, brush, 0, (float)(i * LineHeight));

                g.Dispose();

                image.Save(Path);
                image.Dispose();
                font.Dispose();
                brush.Dispose();
                return Path;
            }
            catch 
            {
                            
            }
            return "";


        }
    }
}
